#include "FrameShower.h"
#include <QDebug>
#include <opencv2/opencv.hpp>
#include "Util.h"
#include "MainWindow.h"


FrameShower::FrameShower(QWidget *parent) : QWidget(parent)
{
    frameView = new QGraphicsView(this);
    frameScene = new ImageScene();
    layout = new QHBoxLayout(this);
    frameView -> setMouseTracking(true);
    frameView -> setStyleSheet("padding: 0px; border: 0px;");
    frameView -> setScene(frameScene);
    layout -> addWidget(frameView);
    setLayout(layout);

    srcFrameSize = QSize(1, 1);
    SetFrame(std::make_unique<QImage>(reinterpret_cast<const uchar *>("\0\0\0\0"), 1, 1, QImage::Format_RGBA8888));
}

FrameShower::~FrameShower()
{
    delete frameView;
    delete frameScene;
    delete layout;
}

void FrameShower::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);
    ResizeFrame();
}

void FrameShower::ResizeFrame()
{
    GetBestFrameSize();
    frameView -> resize(bestFrameSize);
    frameScene -> setSceneRect(0, 0, bestFrameSize.width(), bestFrameSize.height());
    PutFrameOnView();
}

void FrameShower::GetBestFrameSize()
{
    if(srcFrameSize.height() * size().width() / srcFrameSize.width() < size().height())
    {
        bestFrameSize = QSize(size().width(), int(float(srcFrameSize.height()) * float(size().width()) / float(srcFrameSize.width())));
    }
    else
    {
        bestFrameSize = QSize(int(float(srcFrameSize.width()) * float(size().height()) / float(srcFrameSize.height())), size().height());
    }
}

void FrameShower::PutFrameOnView()
{
    frameScene -> clear();
    frameScene -> addPixmap(frame.scaled(bestFrameSize, Qt::KeepAspectRatio, Qt::SmoothTransformation));
}

void FrameShower::SetSrcFrameSize(const QSize& size)
{
    srcFrameSize = size;
}

void FrameShower::OnMcsUpdate()
{
    std::shared_ptr mcs = MainWindow::Instance() -> GetMcs();
    if(mcs == nullptr)
    {
        srcFrameSize = QSize(1, 1);
        SetFrame(std::make_unique<QImage>(reinterpret_cast<const uchar *>("\0\0\0"), 1, 1, QImage::Format_RGB888));
        return;
    }
    srcFrameSize = QSize(mcs->GetMcsHead().GetWidth(), mcs->GetMcsHead().GetHeight());
    SetFrame(MainWindow::Instance()->GetMcsImage());
}

void FrameShower::SetFrame(std::unique_ptr<QImage> image)
{
    frame = QPixmap::fromImage(*image);
    ResizeFrame();
}

